package com.rxyb.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxyb.authority.constants.AuthorityConstants;
import com.rxyb.authority.db.dao.OpsAuthorityMenuMapper;
import com.rxyb.authority.db.po.OpsAuthorityMenu;
import com.rxyb.authority.db.po.OpsAuthorityRoleMenu;
import com.rxyb.authority.gateway.dto.menu.*;
import com.rxyb.authority.service.OpsAuthorityMenuService;
import com.rxyb.authority.service.OpsAuthorityRoleMenuService;
import com.rxyb.authority.utils.TreeUtils;
import com.rxyb.core.respone.R;
import com.rxyb.core.respone.enums.CommonCode;
import com.rxyb.toolize.VO;
import com.rxyb.toolize.date.DateTime;
import com.rxyb.toolize.date.enums.FormatDate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DUYH
 * @since 2020-05-29
 */
@Slf4j
@Service
public class OpsAuthorityMenuServiceImpl extends ServiceImpl<OpsAuthorityMenuMapper, OpsAuthorityMenu> implements OpsAuthorityMenuService {

    @Autowired(required = false)
    private OpsAuthorityMenuMapper opsAuthorityMenuMapper;
    @Autowired(required = false)
    private OpsAuthorityRoleMenuService opsAuthorityRoleMenuService;

    @Override
    public R<CreateMenuRsp> create(CreateMenuReq createMenuReq) {
        if (VO.isNotBlank(createMenuReq.getMenuId()) && isExsit(createMenuReq.getMenuId())) {
            // 菜单已存在
            return R.failed(CommonCode.MENU_HAS_EXSIT);
        } else if (VO.isNotBlank(createMenuReq.getMenuParentId()) && !"0".equals(createMenuReq.getMenuParentId())) {
            if (!isExsit(createMenuReq.getMenuParentId())) {
                // 父菜单不存在
                return R.failed(CommonCode.MENU_HAS_EXSIT);
            }
        }
        OpsAuthorityMenu record = new OpsAuthorityMenu();
        BeanUtils.copyProperties(createMenuReq, record);
        record.setRowState(AuthorityConstants.ROWSTATE_NORMAL);
        record.setAddTime(DateTime.getDateTime());
        record.setUpdateTime(DateTime.getDateTime());
        int cnt = opsAuthorityMenuMapper.insert(record);
        if (cnt == 1) {
            CreateMenuRsp createMenuRsp = new CreateMenuRsp();
            if (VO.isBlank(createMenuReq.getMenuId())) {
                // 如果menuId为空，则默认等于自增ID
                OpsAuthorityMenu opsAuthorityMenu = new OpsAuthorityMenu();
                opsAuthorityMenu.setId(record.getId());
                opsAuthorityMenu.setMenuId(record.getId().toString());
                opsAuthorityMenuMapper.updateById(opsAuthorityMenu);
                createMenuRsp.setMenuId(record.getId().toString());
            } else {
                createMenuRsp.setMenuId(createMenuReq.getMenuId());
            }
            createMenuRsp.setAddTime(DateTime.getDateFormat(record.getAddTime(), FormatDate.FORMAT_TIME_STR));
            return R.ok(createMenuRsp);
        }
        return R.failed(CommonCode.FAILED);
    }

    @Override
    @CacheEvict(value = "menu", key = "#deleteMenuReq.getMenuId()")
    public R<DeleteMenuRsp> remove(DeleteMenuReq deleteMenuReq) {
        QueryWrapper<OpsAuthorityMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityMenu::getMenuId, deleteMenuReq.getMenuId());
        wrapper.lambda().eq(OpsAuthorityMenu::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        // 需要修改的参数
        OpsAuthorityMenu record = new OpsAuthorityMenu();
        record.setRowState(AuthorityConstants.ROWSTATE_DELETE);
        record.setUpdateTime(DateTime.getDateTime());
        int cnt = opsAuthorityMenuMapper.update(record, wrapper);
        if (cnt == 1) {
            return R.ok(new DeleteMenuRsp());
        }
        return R.failed(CommonCode.FAILED);
    }

    @Override
    @CachePut(value = "menu", key = "#updateMenuReq.getMenuId()")
    public R<UpdateMenuRsp> update(UpdateMenuReq updateMenuReq) {
        QueryWrapper<OpsAuthorityMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityMenu::getMenuId, updateMenuReq.getMenuId());
        wrapper.lambda().eq(OpsAuthorityMenu::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        // 需要修改的参数
        OpsAuthorityMenu record = new OpsAuthorityMenu();
        record.setUpdateTime(DateTime.getDateTime());
        record.setMenuName(updateMenuReq.getMenuName());
        record.setMenuImg(updateMenuReq.getMenuImg());
        record.setMenuUrl(updateMenuReq.getMenuUrl());
        record.setMenuRank(updateMenuReq.getMenuRank());
        record.setMenuParentId(updateMenuReq.getMenuParentId());
        record.setShowMchnt(updateMenuReq.getShowMchnt());
        record.setShowPlatform(updateMenuReq.getShowPlatform());
        int cnt = opsAuthorityMenuMapper.update(record, wrapper);
        if (cnt == 1) {
            return R.ok(new UpdateMenuRsp());
        }
        return R.failed(CommonCode.FAILED);
    }

    @Override
    @Cacheable(cacheNames = {"menu"}, key = "#getMenuInfoReq.getMenuId()", unless = "#result == null")
    public R<GetMenuInfoRsp> query(GetMenuInfoReq getMenuInfoReq) {
        log.info("This is query......");
        QueryWrapper<OpsAuthorityMenu> wrapper = new QueryWrapper<>();
        if (VO.isNotBlank(getMenuInfoReq.getMenuId())) {
            wrapper.lambda().eq(OpsAuthorityMenu::getMenuId, getMenuInfoReq.getMenuId());
        }
        wrapper.lambda().eq(OpsAuthorityMenu::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        OpsAuthorityMenu opsAuthorityMenu = opsAuthorityMenuMapper.selectOne(wrapper);
        if (null == opsAuthorityMenu) {
            return R.failed(CommonCode.MENU_NOT_EXIST);
        }
        GetMenuInfoRsp getMenuInfoRsp = new GetMenuInfoRsp();
        BeanUtils.copyProperties(opsAuthorityMenu, getMenuInfoRsp);
        getMenuInfoRsp.setAddTime(DateTime.getDateFormat(opsAuthorityMenu.getAddTime(), FormatDate.FORMAT_TIME_STR));
        getMenuInfoRsp.setUpdateTime(DateTime.getDateFormat(opsAuthorityMenu.getUpdateTime(), FormatDate.FORMAT_TIME_STR));
        /*查询该菜单下的子菜单*/
        QueryWrapper<OpsAuthorityMenu> wrapper2 = new QueryWrapper<>();
        wrapper2.lambda().eq(OpsAuthorityMenu::getMenuParentId, opsAuthorityMenu.getMenuId());
        wrapper2.lambda().eq(OpsAuthorityMenu::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        final List<OpsAuthorityMenu> opsAuthorityMenus = opsAuthorityMenuMapper.selectList(wrapper2);
        if (opsAuthorityMenus != null && opsAuthorityMenus.size() != 0) {
            List<AuthorityMenuVo> resultList = new ArrayList<>();
            for (OpsAuthorityMenu record : opsAuthorityMenus) {
                resultList.add(potovo(record));
            }
            getMenuInfoRsp.setSubMenu(resultList);
        }
        return R.ok(getMenuInfoRsp);
    }

    @Override
    public R<GetMenuListRsp> list(GetMenuListReq getMenuListReq) {
        GetMenuListRsp getMenuListRsp = new GetMenuListRsp();
        QueryWrapper<OpsAuthorityMenu> wrapper = new QueryWrapper<>();
        List<AuthorityMenuVo> resultList = new ArrayList<>();
        /*条件搜索*/
        if (VO.isNotBlank(getMenuListReq.getMenuParentId())) {
            wrapper.lambda().eq(OpsAuthorityMenu::getMenuParentId, getMenuListReq.getMenuParentId());
        }
        if (null != getMenuListReq.getMenuRank() && 0 != getMenuListReq.getMenuRank()) {
            wrapper.lambda().eq(OpsAuthorityMenu::getMenuRank, getMenuListReq.getMenuRank());
        }
        if (null != getMenuListReq.getShowMchnt() && 0 != getMenuListReq.getShowMchnt()) {
            wrapper.lambda().eq(OpsAuthorityMenu::getShowMchnt, getMenuListReq.getShowMchnt());
        }
        if (null != getMenuListReq.getShowPlatform() && 0 != getMenuListReq.getShowPlatform()) {
            wrapper.lambda().eq(OpsAuthorityMenu::getShowPlatform, getMenuListReq.getShowPlatform());
        }
        if (VO.isNotBlank(getMenuListReq.getAddTime())) {
            wrapper.lambda().le(OpsAuthorityMenu::getAddTime, getMenuListReq.getAddTime() + "240000");
            wrapper.lambda().ge(OpsAuthorityMenu::getAddTime, getMenuListReq.getAddTime() + "000000");
        }
        if (VO.isNotBlank(getMenuListReq.getUpdateTime())) {
            wrapper.lambda().le(OpsAuthorityMenu::getUpdateTime, getMenuListReq.getUpdateTime() + "240000");
            wrapper.lambda().ge(OpsAuthorityMenu::getUpdateTime, getMenuListReq.getUpdateTime() + "000000");
        }
        if (VO.isNotBlank(getMenuListReq.getMenuName())) {
            wrapper.lambda().like(OpsAuthorityMenu::getMenuName, "%" + getMenuListReq.getMenuName().trim() + "%");
        }
        if (VO.isNotBlank(getMenuListReq.getMenuUrl())) {
            wrapper.lambda().like(OpsAuthorityMenu::getMenuUrl, "%" + getMenuListReq.getMenuUrl().trim() + "%");
        }
        wrapper.lambda().eq(OpsAuthorityMenu::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        // 排序
        wrapper.orderByDesc("update_time");
        //总页数+总记录数
        Page<OpsAuthorityMenu> page = new Page<>(getMenuListReq.getPageNo(), getMenuListReq.getPageSize());
        IPage<OpsAuthorityMenu> iPage = opsAuthorityMenuMapper.selectPage(page, wrapper);
        final List<OpsAuthorityMenu> list = iPage.getRecords();
        if (list != null && list.size() != 0) {
            for (OpsAuthorityMenu record : list) {
                resultList.add(potovo(record));
            }
        }
        getMenuListRsp.setSize(iPage.getTotal());
        getMenuListRsp.setList(resultList);
        return R.ok(getMenuListRsp);
    }

    @Override
    public R<GetRoleMenuListRsp> tree(GetRoleMenuListReq getRoleMenuListReq) {
        GetRoleMenuListRsp getRoleMenuListRsp = new GetRoleMenuListRsp();
        QueryWrapper<OpsAuthorityMenu> wrapper = new QueryWrapper<>();
        List<AuthorityMenuVo> resultList = new ArrayList<>();
        /*根据菜单路径查询有权限的角色*/
        List<String> menuIds = queryMenusByRole(getRoleMenuListReq.getRoleId());
        if (menuIds == null || menuIds.size() == 0) {
            getRoleMenuListRsp.setList(resultList);
            return R.ok(getRoleMenuListRsp);
        }
        wrapper.lambda().in(OpsAuthorityMenu::getMenuId, menuIds);
        // 排序
        wrapper.orderByAsc("menu_rank,menu_parent_id");
        final List<OpsAuthorityMenu> list = opsAuthorityMenuMapper.selectList(wrapper);
        Map<String, List<AuthorityMenuVo>> map = new TreeMap<>();
        if (list != null && list.size() != 0) {
            for (OpsAuthorityMenu record : list) {
                resultList.add(potovo(record));
            }
        }
        // 按组重写菜单
        getRoleMenuListRsp.setList(TreeUtils.listToTree(resultList));
        return R.ok(getRoleMenuListRsp);
    }

    @Override
    public List<OpsAuthorityMenu> queryMenusByUrl(String menuUrl) {
        QueryWrapper<OpsAuthorityMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(OpsAuthorityMenu::getMenuUrl, menuUrl).eq(OpsAuthorityMenu::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        return opsAuthorityMenuMapper.selectList(wrapper);
    }

    @Override
    @Cacheable(cacheNames = {"role"}, key = "#roleId", unless = "#result == null")
    public List<String> queryMenusByRole(String roleId) {
        List<String> roleIds = new ArrayList<>();
        roleIds.add(roleId);
        // 查询菜单对应的角色
        final List<OpsAuthorityRoleMenu> opsAuthorityRoleMenus = opsAuthorityRoleMenuService.queryMenusByRole(roleIds);
        if (null == opsAuthorityRoleMenus || 0 == opsAuthorityRoleMenus.size()) {
            return new ArrayList<>();
        }
        final List<String> menuIds = opsAuthorityRoleMenus.stream().map(OpsAuthorityRoleMenu::getMenuId).distinct().collect(Collectors.toList());
        return menuIds;
    }

    @Cacheable(cacheNames = {"menu"}, key = "#menuId")
    public boolean isExsit(String menuId) {
        QueryWrapper<OpsAuthorityMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OpsAuthorityMenu::getMenuId, menuId).eq(OpsAuthorityMenu::getRowState, AuthorityConstants.ROWSTATE_NORMAL);
        List<OpsAuthorityMenu> opsAuthorityMenus = opsAuthorityMenuMapper.selectList(wrapper);
        return opsAuthorityMenus.size() > 0;
    }


    public AuthorityMenuVo potovo(OpsAuthorityMenu record) {
        AuthorityMenuVo menu = new AuthorityMenuVo();
        BeanUtils.copyProperties(record, menu);
        menu.setAddTime(DateTime.getDateFormat(record.getAddTime(), FormatDate.FORMAT_TIME_STR));
        menu.setUpdateTime(DateTime.getDateFormat(record.getUpdateTime(), FormatDate.FORMAT_TIME_STR));
        return menu;
    }

}
